package com.imonsoft.sqm.web.excel.SupplierExcel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.imonsoft.common.constant.CCommon;
import com.imonsoft.common.constant.ConstantDict;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.AjaxUtil;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.pojo.basedata.Dictionary;
import com.imonsoft.sqm.service.basedata.DictionaryService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import com.imonsoft.sqm.service.excel.BaseExcel.ExcelService;
import com.imonsoft.sqm.service.excel.SupplierExcel.SupplierExcelService;

@Controller
@RequestMapping("/excel/supplierExcel")
public class SupplierExcelController {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private ExcelService excelService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private SupplierExcelService supplierExcelService;

	/**
	 * 供应商导入
	 * 
	 * @param model
	 */
	@RequestMapping(value = "/supplierImportUI.do")
	public void supplierImportUI(ModelMap model) {
		List<Dictionary> dictMaterialGroupList = dictionaryService.findDictionaryByType(ConstantDict.SUPPLIER_MATERIAL_GROUP);
		model.put("dictMaterialGroupList", dictMaterialGroupList);
		SupplierImportDto supplierImportDto = new SupplierImportDto();
		model.put("supplierImportDto", supplierImportDto);
	}

	/**
	 * description Excel模版下载 on 2013-5-30
	 * 
	 * @a uthor zhouwei
	 */
	@RequestMapping(value = "/excelModel.do", method = RequestMethod.POST)
	public void excelModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		excelService.loadExcelModel(request, response, ConstantSqm.EXCEL_SUPPLIER);
	}

	/**
	 * description Excel导入操作 on 2013-5-14
	 * 
	 * @author zhouwei
	 */
	@RequestMapping(value = "/excelUpload.do", method = RequestMethod.POST)
	public void excelUpload(@RequestParam("file") MultipartFile file, HttpServletResponse response,HttpServletRequest request) throws Exception {
		int maxSize = 200;
		int startRow=1;
		ReturnMessage message = new ReturnMessage();
		String result = "<script type=\"text/javascript\">" + "window.parent.OnUploadCompleted('#reslut#');</script>";
		List<Object[]> contentList = null;
		try {
			contentList = excelService.readExcel(file.getInputStream(),maxSize,startRow);
			Map<String, Object> map = new HashMap<String, Object>();
			List<SupplierImportDto> importList = new ArrayList<SupplierImportDto>();
			List<SupplierImportDto> footerRow = new ArrayList<SupplierImportDto>();
			SupplierImportDto footer = new SupplierImportDto();
			List<SupplierImportDto> errorImportList = new ArrayList<SupplierImportDto>();
			Map<Integer, String> setCode = new HashMap<Integer, String>();// 编码
			List<String> errors = new ArrayList<String>();
			for (Object[] items : contentList) {
				SupplierImportDto dto = new SupplierImportDto();
				dto.setRow(Integer.parseInt(StringUtil.fixup(items[0])));
				dto.setCode(StringUtil.fixup(items[1]));// 供应商编号
				setCode.put(dto.getRow(), StringUtil.fixup(items[1]));
				dto.setName(StringUtil.fixup(items[2]));// 供应商名称
				dto.setMail(StringUtil.fixup(items[3]));// 供应商Email
				dto.setPhone(StringUtil.fixup(items[4]));// 供应商电话
				dto.setLinkman(StringUtil.fixup(items[5]));// 联系人
				dto.setMaterialGroupName(StringUtil.fixup(items[6]));// 材料组
				List<String> messages = supplierExcelService.txCheckData(dto, setCode);
				dto.setHasError(messages.size() > 0);
				importList.add(dto);
				if (dto.isHasError()) {
					errorImportList.add(dto);
				}
				if (errorImportList.size() > maxSize) {
					break;
				}
				errors.addAll(messages);
			}
			footer.setRow(contentList.size());
			footerRow.add(footer);
			map.put("footer", footerRow);
			if (0 == errors.size()) {
				request.getSession().setAttribute(ConstantSqm.SUPPLIER_EXCEL_IMPORT, importList);
			}
			if (contentList.size() <= maxSize) {
				map.put("details", importList);
				if (errors.size() == 0) {
					message.setMsg("数据检查成功。");
				} else {
					map.put("errors", errors);
					message.setMsg("数据检查失败，请查看错误信息。");
				}
			} else {
				if (errors.size() == 0) {
					map.put("details", importList.subList(0, maxSize));
					message.setMsg("数据检查成功，列表中仅显示前500行，更多数据请查看Excel文件。");
				} else {
					if (errorImportList.size() > maxSize) {
						map.put("details", errorImportList.subList(0, errorImportList.size() - 1));
						map.put("errors", errors);
						message.setMsg("数据检查失败，由于错误数据太多，列表中仅显示前500行错误，请仔细检查Excel文件。");
					} else {
						map.put("details", errorImportList);
						map.put("errors", errors);
						message.setMsg("数据检查失败，由于数据量太大，列表中仅显示错误行。");
					}
				}
			}
			message.setObj(map);
			message.setSuccess(true);
		} catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderHTML(response, result.replaceFirst("#reslut#", JsonUtil.bean2json(message)));
	}

	/**
	 * 保存方法
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/ajaxSave.do", method = RequestMethod.POST)
	public void ajaxSave(HttpServletRequest request, HttpServletResponse response) {
		ReturnMessage message = new ReturnMessage();
		try {
			@SuppressWarnings("unchecked")
			List<SupplierImportDto> importList = (List<SupplierImportDto>) request.getSession().getAttribute(ConstantSqm.SUPPLIER_EXCEL_IMPORT);
			supplierService.txInsertForSys(importList);
			request.getSession().removeAttribute(ConstantSqm.SUPPLIER_EXCEL_IMPORT);
			message.setSuccess(true);
		}  catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
	}
}
